package com.sxj.corejava.code12_线程;

/**
 * @author 石小俊
 */
public class Test06_线程间的通信 {

    public static void main(String[] args) {
        Object obj = new Object();
        WaitThread t1 = new WaitThread(obj, "线程1");
        WaitThreadB t2 = new WaitThreadB(obj, "线程2");
        t1.start();
        t2.start();

//        NotifyThread notifyThread = new NotifyThread(obj,"notify线程");
//        notifyThread.start();
        NotifyAllThread notifyAllThread = new NotifyAllThread(obj, "notifyAll线程");
        notifyAllThread.start();
    }

}

class WaitThread extends Thread {
    private Object obj;
    private String name;

    public WaitThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            System.out.println(name + "即将释放锁,进入等待池");
            try {
                // 设置线程等待,进入等待池
                // 可以设置等待时间
//                obj.wait(3000);
                // 也可以不设置等待时间,此时必须等待其他线程唤醒
                obj.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(name + "执行完成");
    }
}

class WaitThreadB extends Thread {
    private Object obj;
    private String name;

    public WaitThreadB(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            System.out.println(name + "即将释放锁,进入等待池");
            try {
                obj.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(name + "执行完成");
    }
}

class NotifyThread extends Thread {
    private Object obj;
    private String name;

    public NotifyThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            // 随机唤醒某一个线程
            // 唤醒的是指定等待池中的某一个线程
            // 如果线程没有进入等待池,无法唤醒
            obj.notify();
            System.out.println(name + "已经随机唤醒了等待池中某一个线程");
        }
    }
}

class NotifyAllThread extends Thread {
    private Object obj;
    private String name;

    public NotifyAllThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        synchronized (obj) {
            // 唤醒对应等待池中所有线程
            obj.notifyAll();
            System.out.println(name + "唤醒了等待池中的所有线程");
        }
    }
}
